package com.smi.cn.satemachine;

import java.util.Map;

import com.smi.cn.satemachine.ReturnVo.RmaStatus;
import com.smi.cn.satemachine.ReturnVo.RmaTrigger;
import com.smi.cn.satemachine.ReturnVo.RmaType;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

/**
 * @author zhangyanfei
 * @date 2017/6/6
 */
@Service
public class RmaStateMachineEngineFactory implements ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * rma事件处理
     *
     * @param rmaId
     * @param rmaTrigger
     * @param context
     * @return
     */
    public ReturnVo fire(int rmaId, RmaTrigger rmaTrigger, StateMachineContext context) {
        /**
         * 调用的入口查询出当前状态
         */
        ReturnVo returnVo=new ReturnVo();
        returnVo.setStatus(RmaStatus.PENDING.value());
        returnVo.setType(RmaType.EXCHANGE.value());
        context.put(MessageKeyEnum.RMA, returnVo);
        Map<String, AbstractStatemachineEngine> rmaStateMachineEngines = applicationContext.getBeansOfType(
            AbstractStatemachineEngine.class);
        boolean accept = false;
        for (AbstractStatemachineEngine rmaStateMachineEngine : rmaStateMachineEngines.values()) {
            if (rmaStateMachineEngine.accept(RmaType.getType(returnVo.getType()))) {
                accept = true;
                rmaStateMachineEngine.fire(returnVo, rmaTrigger, context);
            }
        }
        if (!accept) {
            throw new RuntimeException("Type错误！");
        }
        //注意：目前所有的状态机执行都是同步的，如果存在异步情况，注意此处的数据返回
        return returnVo;
    }
}
